package com.biubiux2;

import com.biubiux2.client.Client;
import com.biubiux2.message.MessageType;
import com.biubiux2.message.MessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author noexcs
 * @since 8/7/2022 4:58 PM
 */
@Slf4j
public class Robot {

    ConnectionManager connectionManager;

    public Robot() {
        connectionManager = new ConnectionManager(this);
    }

    public static AtomicLong totalBroadcastReceived = new AtomicLong(0);

    public AtomicInteger msgBroadcastSendCnt = new AtomicInteger(0);

    public AtomicInteger msgPrivateSendCnt = new AtomicInteger(0);

    public AtomicInteger msgPrivateReceivedCnt = new AtomicInteger(0);

    public AtomicInteger msgBroadcastReceivedCnt = new AtomicInteger(0);

    @Setter
    private CountDownLatch sendCompletionLatch;

    @Setter
    private CountDownLatch loginCompletionLatch;

    public Long firstMsgTime = Long.MAX_VALUE;

    public long lastMsgTime = 0;

    @Setter
    private int privateReceiverLowerLimit = 100001;

    /**
     * inclusive
     */
    @Setter
    private int privateReceiverUpperLimit = 100010;

    @Setter
    @Getter
    private int userId;

    @Setter
    private String password;

    private boolean logged = false;


    public void connect(String host, int port) {
        connectionManager.connect(host, port);
    }

    public void login(int userId, String password, CountDownLatch robotLoginCompletionLatch) {
        this.userId = userId;
        this.password = password;
        loginCompletionLatch = robotLoginCompletionLatch;
        connectionManager.login(userId, password);
    }

    public void logout() {
        connectionManager.logout();
    }

    @Deprecated
    public void run(long duration, TimeUnit timeUnit) {
        Random random = new Random();
        long endTimeMills = System.currentTimeMillis() + timeUnit.toMillis(duration);
        int times = 1;
        while (System.currentTimeMillis() < endTimeMills) {
            int i = random.nextInt(2);
            if (i == 0) {
                // 广播
                for (int j = 0; j < times; j++) {
                    sendBroadcast("这是一条广播消息。", 1, 0);
                }
            } else {
                // 私信
                for (int j = 0; j < times; j++) {
                    // 100001
                    int receiverUserId = privateReceiverLowerLimit + random.nextInt(privateReceiverUpperLimit - privateReceiverLowerLimit);
                    if (receiverUserId != userId) {
                        connectionManager.sendPrivate("hi", receiverUserId);
                        msgPrivateSendCnt.incrementAndGet();
                    }
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println();
        System.out.println("用户" + userId + "共收到" + msgPrivateReceivedCnt + "条私人消息！");
        System.out.println("用户" + userId + "共收到" + msgBroadcastReceivedCnt + "条广播消息！");
        sendCompletionLatch.countDown();
    }

    /**
     * @param times    几次
     * @param duration 每次时间间隔，单位毫秒
     */
    public void sendBroadcast(String content, int times, int duration) {
        for (int i = 0; i < times; i++) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            connectionManager.sendBroadcast(content);
            msgBroadcastSendCnt.incrementAndGet();
            if (sendCompletionLatch != null) {
                sendCompletionLatch.countDown();
            }
        }
    }

    public void sendOneBroadcast(String content) {
        connectionManager.sendBroadcast(content);
        msgBroadcastSendCnt.incrementAndGet();
        if (sendCompletionLatch != null) {
            sendCompletionLatch.countDown();
        }
    }

        public void readBroadcast(String content, int senderUserId) {
        Robot.totalBroadcastReceived.incrementAndGet();
        msgBroadcastReceivedCnt.incrementAndGet();
//        System.out.println("收到一条来自用户" + senderUserId + "的广播消息：" + content);
    }

    public void readPrivate(String content, int senderUserId) {
        msgPrivateReceivedCnt.incrementAndGet();
        System.out.println("收到一条来自用户" + senderUserId + "的私聊消息：" + content);
    }

    public void loginCompletion() {
        if (loginCompletionLatch != null) {
            loginCompletionLatch.countDown();
        }
        logged = true;
        System.out.println(userId + "登录成功！");
    }
}
